// src/utils/request.ts
import http from '@/utils/http'
import type { AxiosRequestConfig } from 'axios'
import type { ApiResponse } from '@/utils/http'

// 关键：把第二个泛型也写成 ApiResponse<T>，并让函数返回 Promise<ApiResponse<T>>
export function get<T = any>(url: string, params?: object, config?: AxiosRequestConfig) {
  return http.get<ApiResponse<T>, ApiResponse<T>>(url, { params, ...config })
}

export function post<T = any>(url: string, data?: object, config?: AxiosRequestConfig) {
  return http.post<ApiResponse<T>, ApiResponse<T>>(url, data, config)
}

export function put<T = any>(url: string, data?: object, config?: AxiosRequestConfig) {
  return http.put<ApiResponse<T>, ApiResponse<T>>(url, data, config)
}

export function del<T = any>(url: string, params?: object, config?: AxiosRequestConfig) {
  return http.delete<ApiResponse<T>, ApiResponse<T>>(url, { params, ...config })
}

/** 上传文件（一般也走统一壳） */
export function upload<T = any>(url: string, formData: FormData, config?: AxiosRequestConfig) {
  return http.post<ApiResponse<T>, ApiResponse<T>>(url, formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
    ...config,
  })
}

/** 下载文件（通常不走统一壳） */
export function download(url: string, params?: object) {
  return http.get<Blob, Blob>(url, { params, responseType: 'blob' })
}

/** 取消请求 */
export function getWithAbort<T = any>(url: string, params?: object) {
  const controller = new AbortController()
  const promise = http.get<ApiResponse<T>, ApiResponse<T>>(url, { params, signal: controller.signal })
  return { promise, cancel: () => controller.abort() }
}
